package com.dk.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author zh
 * @Description TODO
 * @createTime 2023/11/23
 */
@Component
@Primary
public class DyDatasource extends AbstractRoutingDataSource {

    public static  ThreadLocal<String> t = new ThreadLocal<>();

    @Autowired
    private DataSource ds1;

    @Autowired
    private DataSource ds2;

    //返回数据源标识 通过扩展这个方法来实现数据源的切换
    @Override
    protected Object determineCurrentLookupKey() {
        return t.get();
    }

    //数据源加载完毕后立即存入map中，准备数据源路由的操作
    @Override
    public void afterPropertiesSet() {
        //设置数据源集合
        HashMap<Object, Object> map = new HashMap<>();
        map.put("ds1", ds1);
        map.put("ds2", ds2);
        super.setTargetDataSources(map);
        //设置默认数据源
        super.setDefaultTargetDataSource(ds1);

        super.afterPropertiesSet();
    }
}
